using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using SvgToFontConverter.Models;

namespace SvgToFontConverter.Services
{
    /// <summary>
    /// FontForge服务类，负责SVG到TTF的转换
    /// </summary>
    public class FontForgeService
    {
        /// <summary>
        /// 验证FontForge路径是否有效
        /// </summary>
        /// <param name="fontForgePath">FontForge bin目录路径</param>
        /// <returns>是否有效</returns>
        public bool ValidateFontForgePath(string fontForgePath)
        {
            if (string.IsNullOrWhiteSpace(fontForgePath))
                return false;
                
            var ffpythonPath = Path.Combine(fontForgePath, "ffpython.exe");
            return File.Exists(ffpythonPath);
        }
        
        /// <summary>
        /// 将字符串转换为ASCII兼容的PostScript字体名称
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <returns>ASCII兼容的字符串</returns>
        private string ConvertToAsciiCompatible(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
                return "CustomFont";
            
            var result = new StringBuilder();
            
            foreach (char c in input)
            {
                // 只保留ASCII字母、数字和连字符
                if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
                {
                    result.Append(c);
                }
                else if (c == ' ' || c == '-' || c == '_')
                {
                    // 将空格、连字符、下划线统一转换为连字符
                    if (result.Length > 0 && result[result.Length - 1] != '-')
                    {
                        result.Append('-');
                    }
                }
                // 忽略其他字符（包括中文字符）
            }
            
            // 移除开头和结尾的连字符
            var finalResult = result.ToString().Trim('-');
            
            // 如果结果为空或过长，使用默认名称
            if (string.IsNullOrEmpty(finalResult) || finalResult.Length > 60)
            {
                return "CustomFont";
            }
            
            // 确保以字母开头
            if (finalResult.Length > 0 && !char.IsLetter(finalResult[0]))
            {
                finalResult = "Font-" + finalResult;
            }
            
            return finalResult;
        }
        
        /// <summary>
        /// 批量转换多个SVG文件到单个TTF字体
        /// </summary>
        /// <param name="fontForgePath">FontForge bin目录路径</param>
        /// <param name="svgFiles">SVG文件路径列表</param>
        /// <param name="outputFolder">输出文件夹</param>
        /// <param name="fileName">输出文件名（可能包含批次后缀）</param>
        /// <param name="scaleRatio">缩放比例</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <param name="performanceSettings">性能设置</param>
        /// <param name="fontName">字体内部名称（不包含批次后缀）</param>
        /// <param name="fontFamily">字体族名称</param>
        /// <param name="fontAuthor">字体作者</param>
        /// <param name="fontVersion">字体版本</param>
        /// <returns>转换是否成功</returns>
        public async Task<bool> ConvertSvgFilesToFontAsync(string fontForgePath, List<string> svgFiles, 
            string outputFolder, string fileName, double scaleRatio, CancellationToken cancellationToken, PerformanceSettings performanceSettings = null,
            string fontName = null, string fontFamily = null, string fontAuthor = null, string fontVersion = null)
        {
            try
            {
                // 创建临时目录用于预处理
                var tempDir = Path.Combine(Path.GetTempPath(), $"fontforge_preprocess_{Guid.NewGuid():N}");
                Directory.CreateDirectory(tempDir);
                
                try
                {
                    // 预处理SVG文件，应用优化的路径提取和变换
                    var processedSvgFiles = await PreprocessSvgFilesAsync(svgFiles, tempDir);
                    
                    if (processedSvgFiles.Count == 0)
                    {
                        return false;
                    }
                    
                    // 创建批量转换脚本，使用预处理后的文件
                    var scriptPath = await CreateOptimizedBatchScriptAsync(processedSvgFiles, outputFolder, fileName, scaleRatio, performanceSettings, fontName, fontFamily, fontAuthor, fontVersion);
                    
                    // 执行FontForge转换
                    var success = await ExecuteFontForgeScriptAsync(fontForgePath, scriptPath, cancellationToken, performanceSettings);
                    
                    // 清理临时文件
                    if (File.Exists(scriptPath))
                    {
                        File.Delete(scriptPath);
                    }
                    
                    return success;
                }
                finally
                {
                    // 清理临时目录
                    try
                    {
                        if (Directory.Exists(tempDir))
                        {
                            Directory.Delete(tempDir, true);
                        }
                    }
                    catch
                    {
                        // 忽略清理错误
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        
        /// <summary>
        /// 异步转换单个SVG文件到TTF（保留向后兼容性）
        /// </summary>
        /// <param name="fontForgePath">FontForge bin目录路径</param>
        /// <param name="svgFilePath">SVG文件路径</param>
        /// <param name="outputFolder">输出文件夹</param>
        /// <param name="fontFamily">字体族名称</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>转换是否成功</returns>
        public async Task<bool> ConvertSvgToTtfAsync(string fontForgePath, string svgFilePath, 
            string outputFolder, string fontFamily, CancellationToken cancellationToken)
        {
            try
            {
                // 创建临时Python脚本
                var scriptPath = await CreateConversionScriptAsync(svgFilePath, outputFolder, fontFamily);
                
                // 执行FontForge转换
                var success = await ExecuteFontForgeScriptAsync(fontForgePath, scriptPath, cancellationToken);
                
                // 清理临时文件
                if (File.Exists(scriptPath))
                {
                    File.Delete(scriptPath);
                }
                
                return success;
            }
            catch (Exception)
            {
                return false;
            }
        }
        
        /// <summary>
        /// 预处理SVG文件，应用优化的路径提取和变换
        /// </summary>
        /// <param name="svgFiles">原始SVG文件列表</param>
        /// <param name="tempDir">临时目录</param>
        /// <returns>处理后的SVG文件列表</returns>
        private Task<List<string>> PreprocessSvgFilesAsync(List<string> svgFiles, string tempDir)
        {
            var processedFiles = new List<string>();
            
            foreach (var svgFile in svgFiles)
            {
                try
                {
                    var fileName = Path.GetFileNameWithoutExtension(svgFile);
                    Debug.WriteLine($"\n=== 预处理文件: {fileName} ===");
                    
                    if (!File.Exists(svgFile))
                    {
                        Debug.WriteLine($"文件不存在: {svgFile}");
                        continue;
                    }
                    
                    // 读取原始SVG内容
                    var originalSvgContent = File.ReadAllText(svgFile);
                    Debug.WriteLine($"SVG内容长度: {originalSvgContent.Length}");
                    
                    // 直接提取SVG路径数据，应用transform变换
                    var processedPaths = ExtractPathDataDirectly(originalSvgContent);
                    if (processedPaths == null || processedPaths.Count == 0)
                    {
                        Debug.WriteLine($"警告: 文件 {fileName} 无法提取有效的SVG路径");
                        continue;
                    }
                    
                    Debug.WriteLine($"处理后的路径数量: {processedPaths.Count}");
                    
                    // 计算实际字符宽度
                    var actualCharWidth = CalculateCharacterWidth(originalSvgContent);
                    Debug.WriteLine($"实际字符宽度: {actualCharWidth:F2}");
                    
                    // 创建优化的SVG内容
                    var optimizedSvgContent = CreateOptimizedSvg(processedPaths, actualCharWidth);
                    
                    // 保存处理后的SVG文件
                    var outputSvgPath = Path.Combine(tempDir, $"{fileName}.svg");
                    File.WriteAllText(outputSvgPath, optimizedSvgContent);
                    
                    processedFiles.Add(outputSvgPath);
                    Debug.WriteLine($"成功预处理文件: {fileName}");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"预处理文件 {svgFile} 时发生错误: {ex.Message}");
                }
            }
             
             return Task.FromResult(processedFiles);
         }
        
        /// <summary>
        /// 直接提取SVG路径数据，应用transform变换但不进行垂直翻转修正
        /// </summary>
        /// <param name="svgContent">SVG内容</param>
        /// <returns>路径数据列表</returns>
        private List<string> ExtractPathDataDirectly(string svgContent)
        {
            try
            {
                var pathList = new List<string>();
                
                // 首先查找所有的g元素及其transform属性
                var gPattern = @"<g[^>]*transform\s*=\s*[""']([^""']*)[""'][^>]*>([\s\S]*?)</g>";
                var gMatches = Regex.Matches(svgContent, gPattern, RegexOptions.IgnoreCase);
                
                if (gMatches.Count > 0)
                {
                    Debug.WriteLine($"检测到{gMatches.Count}个带transform的g元素");
                    
                    foreach (Match gMatch in gMatches)
                    {
                        var transformAttr = gMatch.Groups[1].Value;
                        var gContent = gMatch.Groups[2].Value;
                        
                        // 解析transform属性中的translate和scale值
                        double translateX = 0, translateY = 0;
                        double scaleX = 1, scaleY = 1;
                        
                        var translateMatch = Regex.Match(transformAttr, @"translate\s*\(\s*([^,\s]+)\s*,?\s*([^\)\s]*)\s*\)", RegexOptions.IgnoreCase);
                        if (translateMatch.Success)
                        {
                            double.TryParse(translateMatch.Groups[1].Value, out translateX);
                            if (translateMatch.Groups[2].Success && !string.IsNullOrEmpty(translateMatch.Groups[2].Value))
                            {
                                double.TryParse(translateMatch.Groups[2].Value, out translateY);
                            }
                        }
                        
                        var scaleMatch = Regex.Match(transformAttr, @"scale\s*\(\s*([^,\s]+)\s*,?\s*([^\)\s]*)\s*\)", RegexOptions.IgnoreCase);
                        if (scaleMatch.Success)
                        {
                            double.TryParse(scaleMatch.Groups[1].Value, out scaleX);
                            if (scaleMatch.Groups[2].Success && !string.IsNullOrEmpty(scaleMatch.Groups[2].Value))
                            {
                                double.TryParse(scaleMatch.Groups[2].Value, out scaleY);
                            }
                            else
                            {
                                scaleY = scaleX; // 如果只有一个值，X和Y使用相同的缩放
                            }
                        }
                        
                        Debug.WriteLine($"解析transform - translate: x={translateX}, y={translateY}, scale: x={scaleX}, y={scaleY}");
                        
                        // 在g元素内容中查找path元素
                        var pathPattern = @"<path[^>]*d\s*=\s*[""']([^""']*)[""'][^>]*>";
                        var pathMatches = Regex.Matches(gContent, pathPattern, RegexOptions.IgnoreCase);
                        
                        foreach (Match pathMatch in pathMatches)
                        {
                            if (pathMatch.Groups.Count > 1)
                            {
                                var pathData = pathMatch.Groups[1].Value.Trim();
                                if (!string.IsNullOrEmpty(pathData))
                                {
                                    // 应用transform变换到路径数据，但不进行垂直翻转修正
                                    var transformedPath = ApplyTransformToPathSimple(pathData, translateX, translateY, scaleX, scaleY);
                                    // 确保路径以Z结尾（如果原路径没有Z，添加一个）
                                    if (!transformedPath.TrimEnd().EndsWith("Z", StringComparison.OrdinalIgnoreCase))
                                    {
                                        transformedPath += " Z";
                                    }
                                    pathList.Add(transformedPath);
                                    Debug.WriteLine($"应用transform后的路径数据: {transformedPath}");
                                }
                            }
                        }
                    }
                }
                else
                {
                    // 普通SVG：提取所有path元素
                    Debug.WriteLine("检测到普通SVG，提取所有路径数据");
                    var pathPattern = @"<path[^>]*d\s*=\s*[""']([^""']*)[""'][^>]*>";
                    var pathMatches = Regex.Matches(svgContent, pathPattern, RegexOptions.IgnoreCase);
                    
                    foreach (Match match in pathMatches)
                    {
                        if (match.Groups.Count > 1)
                        {
                            var pathData = match.Groups[1].Value.Trim();
                            if (!string.IsNullOrEmpty(pathData))
                            {
                                // 确保路径以Z结尾（如果原路径没有Z，添加一个）
                                if (!pathData.TrimEnd().EndsWith("Z", StringComparison.OrdinalIgnoreCase))
                                {
                                    pathData += " Z";
                                }
                                pathList.Add(pathData);
                                Debug.WriteLine($"提取路径数据: {pathData}");
                            }
                        }
                    }
                }
                
                // 如果没有找到任何路径，返回默认矩形路径
                if (pathList.Count == 0)
                {
                    pathList.Add("M100 100h800v800h-800z");
                    Debug.WriteLine("未找到路径，使用默认矩形路径");
                }
                
                Debug.WriteLine($"FontForge提取到 {pathList.Count} 个独立路径");
                return pathList;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"提取路径数据失败: {ex.Message}");
                return new List<string> { "M100 100h800v800h-800z" }; // 默认矩形路径
            }
        }
        
        /// <summary>
        /// 应用transform变换到路径数据，包含垂直翻转修正
        /// </summary>
        /// <param name="pathData">原始路径数据</param>
        /// <param name="translateX">X轴平移</param>
        /// <param name="translateY">Y轴平移</param>
        /// <param name="scaleX">X轴缩放</param>
        /// <param name="scaleY">Y轴缩放</param>
        /// <returns>变换后的路径数据</returns>
        private string ApplyTransformToPathSimple(string pathData, double translateX, double translateY, double scaleX, double scaleY)
        {
            try
            {
                // 移除垂直翻转修正，保持原始SVG坐标系
                
                // 使用正则表达式解析路径命令和坐标
                var result = Regex.Replace(pathData, @"([MLHVCSQTAZ])([^MLHVCSQTAZ]*)", 
                    match =>
                    {
                        var command = match.Groups[1].Value;
                        var coords = match.Groups[2].Value;
                        
                        if (string.IsNullOrWhiteSpace(coords))
                        {
                            return command;
                        }
                        
                        var numbers = Regex.Matches(coords, @"-?\d+(?:\.\d+)?")
                            .Cast<Match>()
                            .Select(m => double.Parse(m.Value))
                            .ToArray();
                        
                        if (numbers.Length == 0)
                        {
                            return match.Value;
                        }
                        
                        var transformedNumbers = new List<double>();
                        var upperCommand = command.ToUpper();
                        
                        switch (upperCommand)
                        {
                            case "M": // MoveTo
                            case "L": // LineTo
                                for (int i = 0; i < numbers.Length; i += 2)
                                {
                                    if (i + 1 < numbers.Length)
                                    {
                                        var x = numbers[i] * scaleX + translateX;
                                        var y = numbers[i + 1] * scaleY + translateY;
                                        // 移除垂直翻转修正，保持原始方向
                                        transformedNumbers.Add(x);
                                        transformedNumbers.Add(y);
                                    }
                                }
                                break;
                            case "H": // Horizontal LineTo
                                for (int i = 0; i < numbers.Length; i++)
                                {
                                    transformedNumbers.Add(numbers[i] * scaleX + translateX);
                                }
                                break;
                            case "V": // Vertical LineTo
                                for (int i = 0; i < numbers.Length; i++)
                                {
                                    var y = numbers[i] * scaleY + translateY;
                                    // 移除垂直翻转修正，保持原始方向
                                    transformedNumbers.Add(y);
                                }
                                break;
                            case "C": // CurveTo
                                for (int i = 0; i < numbers.Length; i += 6)
                                {
                                    if (i + 5 < numbers.Length)
                                    {
                                        var x1 = numbers[i] * scaleX + translateX;
                                        var y1 = numbers[i + 1] * scaleY + translateY;
                                        var x2 = numbers[i + 2] * scaleX + translateX;
                                        var y2 = numbers[i + 3] * scaleY + translateY;
                                        var x = numbers[i + 4] * scaleX + translateX;
                                        var y = numbers[i + 5] * scaleY + translateY;
                                        
                                        // 移除垂直翻转修正，保持原始方向
                                        
                                        transformedNumbers.Add(x1);
                                        transformedNumbers.Add(y1);
                                        transformedNumbers.Add(x2);
                                        transformedNumbers.Add(y2);
                                        transformedNumbers.Add(x);
                                        transformedNumbers.Add(y);
                                    }
                                }
                                break;
                            case "Q": // QuadraticCurveTo
                                for (int i = 0; i < numbers.Length; i += 4)
                                {
                                    if (i + 3 < numbers.Length)
                                    {
                                        var x1 = numbers[i] * scaleX + translateX;
                                        var y1 = numbers[i + 1] * scaleY + translateY;
                                        var x = numbers[i + 2] * scaleX + translateX;
                                        var y = numbers[i + 3] * scaleY + translateY;
                                        
                                        // 移除垂直翻转修正，保持原始方向
                                        
                                        transformedNumbers.Add(x1);
                                        transformedNumbers.Add(y1);
                                        transformedNumbers.Add(x);
                                        transformedNumbers.Add(y);
                                    }
                                }
                                break;
                            case "Z": // ClosePath
                                return command;
                            default:
                                // 对于其他命令，简单地应用变换
                                for (int i = 0; i < numbers.Length; i += 2)
                                {
                                    if (i + 1 < numbers.Length)
                                    {
                                        var x = numbers[i] * scaleX + translateX;
                                        var y = numbers[i + 1] * scaleY + translateY;
                                        // 移除垂直翻转修正，保持原始方向
                                        transformedNumbers.Add(x);
                                        transformedNumbers.Add(y);
                                    }
                                }
                                break;
                        }
                        
                        return command + string.Join(",", transformedNumbers.Select(n => n.ToString("F2")));
                    }, RegexOptions.IgnoreCase);
                
                return result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"应用transform变换失败: {ex.Message}");
                return pathData; // 返回原始路径数据
            }
        }
        
        /// <summary>
        /// 计算字符宽度（考虑transform缩放的改进版本）
        /// </summary>
        /// <param name="svgContent">SVG内容</param>
        /// <returns>实际字符宽度</returns>
        private double CalculateCharacterWidth(string svgContent)
        {
            try
            {
                // 解析viewBox
                var viewBoxMatch = Regex.Match(svgContent, 
                    @"viewBox\s*=\s*[""']([^""']*)[""']", 
                    RegexOptions.IgnoreCase);
                    
                double sourceWidth = 100, sourceHeight = 100;
                
                if (viewBoxMatch.Success)
                {
                    var viewBoxValues = viewBoxMatch.Groups[1].Value.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (viewBoxValues.Length >= 4)
                    {
                        double.TryParse(viewBoxValues[2], out sourceWidth);
                        double.TryParse(viewBoxValues[3], out sourceHeight);
                    }
                }
                else
                {
                    // 如果没有viewBox，尝试解析width和height属性
                    var widthMatch = Regex.Match(svgContent, 
                        @"width\s*=\s*[""']([^""']*)[""']", 
                        RegexOptions.IgnoreCase);
                    var heightMatch = Regex.Match(svgContent, 
                        @"height\s*=\s*[""']([^""']*)[""']", 
                        RegexOptions.IgnoreCase);
                    
                    if (widthMatch.Success && heightMatch.Success)
                    {
                        var widthStr = widthMatch.Groups[1].Value.Replace("px", "").Replace("pt", "");
                        var heightStr = heightMatch.Groups[1].Value.Replace("px", "").Replace("pt", "");
                        double.TryParse(widthStr, out sourceWidth);
                        double.TryParse(heightStr, out sourceHeight);
                    }
                }
                
                // 检查是否有g元素的transform缩放
                double transformScaleX = 1.0, transformScaleY = 1.0;
                var gPattern = @"<g[^>]*transform\s*=\s*[""']([^""']*)[""'][^>]*>";
                var gMatch = Regex.Match(svgContent, gPattern, RegexOptions.IgnoreCase);
                
                if (gMatch.Success)
                {
                    var transformAttr = gMatch.Groups[1].Value;
                    var scaleMatch = Regex.Match(transformAttr, @"scale\s*\(\s*([^,\s]+)\s*,?\s*([^\)\s]*)\s*\)", RegexOptions.IgnoreCase);
                    if (scaleMatch.Success)
                    {
                        double.TryParse(scaleMatch.Groups[1].Value, out transformScaleX);
                        if (scaleMatch.Groups[2].Success && !string.IsNullOrEmpty(scaleMatch.Groups[2].Value))
                        {
                            double.TryParse(scaleMatch.Groups[2].Value, out transformScaleY);
                        }
                        else
                        {
                            transformScaleY = transformScaleX; // 如果只有一个值，X和Y使用相同的缩放
                        }
                        
                        Debug.WriteLine($"检测到transform缩放: scaleX={transformScaleX}, scaleY={transformScaleY}");
                    }
                }
                
                // 应用transform缩放到源尺寸
                double effectiveWidth = sourceWidth * Math.Abs(transformScaleX);
                double effectiveHeight = sourceHeight * Math.Abs(transformScaleY);
                
                Debug.WriteLine($"原始尺寸: {sourceWidth}x{sourceHeight}, 应用transform后: {effectiveWidth:F2}x{effectiveHeight:F2}");
                
                // 固定字符高度为750单位，锁定纵横比缩放宽度
                double targetCharHeight = 750.0;  // 固定高度750单位
                double scale = targetCharHeight / effectiveHeight;
                
                // 确保最小缩放比例
                double minScale = Math.Min(targetCharHeight / effectiveHeight, (1000 * 0.5) / Math.Max(effectiveWidth, effectiveHeight));
                if (scale < minScale)
                {
                    scale = minScale;
                }
                
                // 限制最大缩放比例
                if (scale > 20.0)
                {
                    scale = 20.0;
                }
                
                // 计算实际字符宽度（锁定纵横比）
                double finalWidth = effectiveWidth * scale;
                Debug.WriteLine($"最终字符宽度: {finalWidth:F2}");
                
                return finalWidth;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"计算字符宽度失败: {ex.Message}");
                return 1000; // 默认宽度
            }
        }
        
        /// <summary>
        /// 创建优化的SVG内容
        /// </summary>
        /// <param name="pathDataList">路径数据列表</param>
        /// <param name="width">字符宽度</param>
        /// <returns>优化的SVG内容</returns>
        private string CreateOptimizedSvg(List<string> pathDataList, double width)
        {
            var svgContent = new StringBuilder();
            
            // 为了确保右线位置正确，viewBox宽度应该稍大于字符宽度
            var viewBoxWidth = Math.Max(width + 100, 1000); // 至少1000单位宽度，或字符宽度+100边距
            var viewBoxHeight = 750; // 使用750作为固定高度，保持纵横比
            
            // 根据无镂空SVG的结构，使用clipPath和统一的g元素
            svgContent.AppendLine($"<svg width=\"{viewBoxWidth:F0}\" height=\"{viewBoxHeight}\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xml:space=\"preserve\" overflow=\"hidden\">");
            
            // 添加clipPath定义
            svgContent.AppendLine("<defs>");
            svgContent.AppendLine("<clipPath id=\"clip0\">");
            svgContent.AppendLine($"<rect x=\"0\" y=\"0\" width=\"{viewBoxWidth:F0}\" height=\"{viewBoxHeight}\"/>");
            svgContent.AppendLine("</clipPath>");
            svgContent.AppendLine("</defs>");
            
            // 使用统一的g元素，应用clipPath和transform
            svgContent.AppendLine($"<g clip-path=\"url(#clip0)\" transform=\"matrix(1 0 0 1 0 0)\">");
            
            // 处理路径数据
            if (pathDataList != null && pathDataList.Count > 0)
            {
                // 清理路径数据
                var cleanedPaths = new List<string>();
                foreach (var path in pathDataList)
                {
                    if (!string.IsNullOrWhiteSpace(path))
                    {
                        var cleanPath = path.Trim();
                        // 确保路径以Z结尾
                        if (!cleanPath.EndsWith("Z", StringComparison.OrdinalIgnoreCase) && 
                            !cleanPath.EndsWith("z"))
                        {
                            cleanPath += " Z";
                        }
                        cleanedPaths.Add(cleanPath);
                    }
                }
                
                if (cleanedPaths.Count > 0)
                {
                    // 为每个路径创建单独的path元素，都使用fill-rule="evenodd"
                    foreach (var pathData in cleanedPaths)
                    {
                        svgContent.AppendLine($"<path d=\"{pathData}\" fill-rule=\"evenodd\" transform=\"matrix(1 0 0 1 0 0)\"/>");
                    }
                }
                else
                {
                    // 如果没有有效路径，创建默认矩形
                    svgContent.AppendLine("<path d=\"M100 100h800v800h-800Z\" fill-rule=\"evenodd\" transform=\"matrix(1 0 0 1 0 0)\"/>");
                }
            }
            else
            {
                // 如果没有路径数据，创建默认矩形
                svgContent.AppendLine("<path d=\"M100 100h800v800h-800Z\" fill-rule=\"evenodd\" transform=\"matrix(1 0 0 1 0 0)\"/>");
            }
            
            svgContent.AppendLine("</g>");
            svgContent.AppendLine("</svg>");
            
            return svgContent.ToString();
        }
        

        
        /// <summary>
        /// 新增ConvertSvgToFontAsync方法，调用预处理功能
        /// </summary>
        public async Task<bool> ConvertSvgToFontAsync(List<string> svgFiles, string outputFolder, string fileName, CancellationToken cancellationToken = default, PerformanceSettings performanceSettings = null, string fontName = null, string fontFamily = null, string fontAuthor = null, string fontVersion = null)
        {
            try
            {
                Debug.WriteLine($"\n=== FontForge 转换开始 ===");
                Debug.WriteLine($"输入文件数量: {svgFiles.Count}");
                Debug.WriteLine($"输出目录: {outputFolder}");
                Debug.WriteLine($"输出文件名: {fileName}");
                
                if (svgFiles == null || svgFiles.Count == 0)
                {
                    Debug.WriteLine("错误: 没有提供SVG文件");
                    return false;
                }
                
                // 确保输出目录存在
                Directory.CreateDirectory(outputFolder);
                
                // 创建临时目录用于预处理
                var tempDir = Path.Combine(Path.GetTempPath(), $"fontforge_preprocess_{Guid.NewGuid():N}");
                Directory.CreateDirectory(tempDir);
                
                try
                {
                    // 预处理SVG文件，应用优化的路径提取和变换
                    Debug.WriteLine("开始预处理SVG文件...");
                    var processedSvgFiles = await PreprocessSvgFilesAsync(svgFiles, tempDir);
                    
                    if (processedSvgFiles.Count == 0)
                    {
                        Debug.WriteLine("错误: 没有成功预处理任何SVG文件");
                        return false;
                    }
                    
                    Debug.WriteLine($"成功预处理 {processedSvgFiles.Count} 个SVG文件");
                    
                    // 使用优化的批量转换脚本，传入预处理后的文件
                    var scriptPath = await CreateOptimizedBatchScriptAsync(processedSvgFiles, outputFolder, fileName, 1.0, performanceSettings, fontName, fontFamily, fontAuthor, fontVersion);
                    
                    Debug.WriteLine($"生成的脚本路径: {scriptPath}");
                    
                    // 执行FontForge脚本
                    var success = await ExecuteFontForgeScriptAsync("ffpython", scriptPath, cancellationToken, performanceSettings);
                    
                    // 清理临时脚本文件
                    try
                    {
                        if (File.Exists(scriptPath))
                        {
                            File.Delete(scriptPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"清理临时脚本文件失败: {ex.Message}");
                    }
                    
                    Debug.WriteLine($"FontForge 转换结果: {(success ? "成功" : "失败")}");
                    return success;
                }
                finally
                {
                    // 清理临时目录
                    try
                    {
                        if (Directory.Exists(tempDir))
                        {
                            Directory.Delete(tempDir, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"清理临时目录失败: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"FontForge转换过程中发生错误: {ex.Message}");
                Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return false;
            }
        }
        
        /// <summary>
        /// 创建优化的批量转换脚本（提高大文件处理性能）
        /// </summary>
        private Task<string> CreateOptimizedBatchScriptAsync(List<string> svgFiles, string outputFolder, string fileName, double scaleRatio, PerformanceSettings performanceSettings = null, string fontName = null, string fontFamily = null, string fontAuthor = null, string fontVersion = null)
        {
            var scriptPath = Path.Combine(Path.GetTempPath(), $"optimized_batch_convert_{Guid.NewGuid():N}.py");
            
            // 构建SVG文件列表
            var svgFilesList = string.Join(",\n        ", svgFiles.Select(f => $"r'{f.Replace("\\", "/")}'"));
            
            // 获取性能参数
            var progressInterval = performanceSettings?.ProgressReportInterval ?? 100;
            var cleanupInterval = performanceSettings?.MemoryCleanupInterval ?? 1000;
            
            // 设置字体属性 - 转换为ASCII兼容的名称
            var actualFontName = ConvertToAsciiCompatible(fontName ?? "CustomFont");
            var actualFontFamily = ConvertToAsciiCompatible(fontFamily ?? "CustomFont");
            var actualFontDisplayName = fontFamily ?? "Custom Font"; // 显示名称可以保留原文
            var actualFontAuthor = fontAuthor ?? "Unknown";
            var actualFontVersion = fontVersion ?? "1.0";
            var outputFileName = fileName ?? actualFontFamily;
            
            var script = $@"# -*- coding: utf-8 -*-
# 优化的批量SVG转字体脚本 - 提高大文件处理性能
import fontforge, os, psMat, gc
import sys

def main():
    '''
    主函数 - 优化的批量转换
    '''
    # 定义参数
    img_list = [
        {svgFilesList}
    ]
    output_dir = r'{outputFolder.Replace("\\", "/")}'
    
    total_files = len(img_list)
    print('开始处理，总文件数量: %d' % total_files)
    
    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 创建单个字体对象来包含所有字符
    font = fontforge.font()
    font.encoding = 'UnicodeFull'
    font.version = '{actualFontVersion}'
    font.weight = 'Regular'
    font.fontname = '{actualFontName}'
    font.familyname = '{actualFontFamily}'
    font.fullname = '{actualFontDisplayName}'
    font.copyright = 'Created by {actualFontAuthor}'
    
    # 设置字体尺寸为固定高度750单位
    font.ascent = 750
    font.descent = 0
    font.em = 750  # 设置em单位为750
    
    # 优化设置
    processed_count = 0
    error_count = 0
    
    try:
        for index, img_path in enumerate(img_list):
            try:
                # 每处理指定数量文件输出一次进度
                if index % {progressInterval} == 0 or index == total_files - 1:
                    progress = (index + 1) * 100 // total_files
                    print('处理进度: %d%% (%d/%d)' % (progress, index + 1, total_files))
                    sys.stdout.flush()  # 强制刷新输出
                
                # 获取unicode
                codestr = os.path.splitext(os.path.basename(img_path))[0]
                try:
                    code = int(codestr, 16)
                except ValueError:
                    print('跳过无效文件名: %s' % codestr)
                    error_count += 1
                    continue
                
                # 检查文件是否存在
                if not os.path.exists(img_path):
                    print('文件不存在: %s' % img_path)
                    error_count += 1
                    continue
                
                # 在同一个字体中创建字符
                glyph = font.createChar(code, ""uni""+codestr)
                
                try:
                    glyph.importOutlines(img_path)
                    
                    # 注释：已移除路径去重逻辑以避免路径重合部分丢失形成镂空
                        
                except Exception as e:
                    print('导入轮廓失败: %s, 错误: %s' % (img_path, str(e)))
                    error_count += 1
                    continue
                
                # 获取字符边界框并进行优化处理
                try:
                    bbox = glyph.boundingBox()
                    if bbox[0] != bbox[2] and bbox[1] != bbox[3]:  # 确保边界框有效
                        # 计算当前字符的宽度和高度
                        char_width = bbox[2] - bbox[0]
                        char_height = bbox[3] - bbox[1]
                        
                        # 字体标准尺寸（固定高度750单位）
                        target_height = 750.0  # 固定字符高度为750单位
                        ascent = 750   # 基线到顶线的距离
                        descent = 0    # 基线到底线的距离
                        
                        # 计算缩放比例，固定高度750，锁定纵横比缩放宽度
                        scale_to_fit = target_height / char_height if char_height > 0 else 1.0
                        
                        # 应用用户设置的缩放比例
                        scale_ratio = {scaleRatio}
                        final_scale = scale_to_fit * scale_ratio
                        
                        # 先移动到原点
                        move_to_origin = psMat.translate(-bbox[0], -bbox[1])
                        glyph.transform(move_to_origin)
                        
                        # 应用缩放
                        if final_scale != 1.0:
                            scale_matrix = psMat.scale(final_scale, final_scale)
                            glyph.transform(scale_matrix)
                        
                        # 重新获取缩放后的边界框
                        new_bbox = glyph.boundingBox()
                        if new_bbox[0] != new_bbox[2] and new_bbox[1] != new_bbox[3]:
                            # 移动到基线位置（字符底部对齐基线）
                            baseline_offset = -new_bbox[1]
                            baseline_matrix = psMat.translate(0, baseline_offset)
                            glyph.transform(baseline_matrix)
                    
                    # 设置字符宽度
                    glyph.width = int(glyph.boundingBox()[2]) if glyph.boundingBox()[0] != glyph.boundingBox()[2] else 500
                    
                except Exception as e:
                    print('处理字符边界框失败: %s, 错误: %s' % (img_path, str(e)))
                    # 设置默认宽度
                    glyph.width = 500
                
                processed_count += 1
                
                # 每处理指定数量字符进行一次垃圾回收，释放内存
                if processed_count % {cleanupInterval} == 0:
                    gc.collect()
                    
            except Exception as e:
                print('处理文件时发生错误: %s, 错误: %s' % (img_path, str(e)))
                error_count += 1
                continue
        
        print('字符处理完成，成功: %d, 失败: %d' % (processed_count, error_count))
        
        # 生成单个包含所有字符的TTF文件
        output_path = os.path.join(output_dir, '{outputFileName}.ttf')
        print('开始生成字体文件...')
        font.generate(output_path)
        print('字体文件生成完成: %s' % output_path)
        
    except Exception as e:
        print('转换过程中发生严重错误: %s' % str(e))
        return False
    finally:
        # 关闭字体对象
        try:
            font.close()
        except:
            pass
        
        # 强制垃圾回收
        gc.collect()
        
    print('全部处理结束')
    return processed_count > 0

if __name__ == '__main__':
    '''
    程序入口
    '''
    try:
        success = main()
        print('转换完成，成功状态:', success)
        sys.exit(0 if success else 1)
    except Exception as e:
        print('转换过程中发生错误: %s' % str(e))
        sys.exit(1)
";
            
            File.WriteAllText(scriptPath, script);
            return Task.FromResult(scriptPath);
        }
        
        /// <summary>
        /// 创建批量转换脚本（将所有SVG合并到一个字体文件中）- 保留原版本
        /// </summary>
        private Task<string> CreateOriginalStyleBatchScriptAsync(List<string> svgFiles, string outputFolder, string fontFamily, double scaleRatio)
        {
            var scriptPath = Path.Combine(Path.GetTempPath(), $"batch_convert_{Guid.NewGuid():N}.py");
            
            // 构建SVG文件列表
            var svgFilesList = string.Join(",\n        ", svgFiles.Select(f => $"r'{f.Replace("\\", "/")}'"));
            
            // 转换字体名称为ASCII兼容格式
            var asciiFontFamily = ConvertToAsciiCompatible(fontFamily ?? "CustomFont");
            
            var script = $@"# -*- coding: utf-8 -*-
# 将所有SVG字符合并到一个字体文件中
import fontforge, os, psMat

def main():
    '''
    主函数 - 合并所有SVG到单个字体
    '''
    # 定义参数
    img_list = [
        {svgFilesList}
    ]
    output_dir = r'{outputFolder.Replace("\\", "/")}'
    
    print('当前总图片数量： %d' % len(img_list))
    
    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 创建单个字体对象来包含所有字符
    font = fontforge.font()
    font.encoding = 'UnicodeFull'
    font.version = '1.0'
    font.weight = 'Regular'
    font.fontname = '{asciiFontFamily}'
    font.familyname = '{asciiFontFamily}'
    font.fullname = '{fontFamily ?? "Custom Font"}'
    
    # 循环处理图片，将所有字符添加到同一个字体中
    index = 0
    
    for img_path in img_list:  
        print('当前处理 '+os.path.basename(img_path))
        
        # 获取unicode
        codestr = os.path.splitext(os.path.basename(img_path))[0]
        try:
            code = int(codestr, 16)
        except ValueError:
            print(f'跳过无效文件名: {{{{codestr}}}}')
            continue
        
        # 在同一个字体中创建字符
        glyph = font.createChar(code, ""uni""+codestr)
        glyph.importOutlines(img_path)
        
        # 获取字符边界框
        bbox = glyph.boundingBox()
        if bbox[0] != bbox[2] and bbox[1] != bbox[3]:  # 确保边界框有效
            # 计算当前字符的宽度和高度
            char_width = bbox[2] - bbox[0]
            char_height = bbox[3] - bbox[1]
            
            # 字体标准尺寸（FontForge默认值）
            ascent = 800   # 基线到顶线的距离
            descent = 200  # 基线到底线的距离
            
            # 计算缩放比例，保持横纵比
            scale_to_fit = min(ascent / char_height, 1000 / char_width) if char_height > 0 and char_width > 0 else 1.0
            
            # 应用用户设置的缩放比例
            scale_ratio = {scaleRatio}
            final_scale = scale_to_fit * scale_ratio
            
            # 先移动到原点
            move_to_origin = psMat.translate(-bbox[0], -bbox[1])
            glyph.transform(move_to_origin)
            
            # 应用缩放
            if final_scale != 1.0:
                scale_matrix = psMat.scale(final_scale, final_scale)
                glyph.transform(scale_matrix)
            
            # 重新获取缩放后的边界框
            new_bbox = glyph.boundingBox()
            if new_bbox[0] != new_bbox[2] and new_bbox[1] != new_bbox[3]:
                new_height = new_bbox[3] - new_bbox[1]
                
                # 移动到基线位置（字符底部对齐基线）
                baseline_offset = -new_bbox[1]
                baseline_matrix = psMat.translate(0, baseline_offset)
                glyph.transform(baseline_matrix)
        
        # 设置字符宽度
        glyph.width = int(glyph.boundingBox()[2]) if glyph.boundingBox()[0] != glyph.boundingBox()[2] else 500
        
        index +=1
        print('当前处理完 %d 张图片' % index)
    
    # 生成单个包含所有字符的TTF文件
    output_path = os.path.join(output_dir, '{asciiFontFamily}.ttf')
    font.generate(output_path)
    print(f'生成字体文件: {{{{output_path}}}}')
    
    # 关闭字体对象
    font.close()
        
    print('全部处理结束')
    return True

if __name__ == '__main__':
    '''
    程序入口
    '''
    try:
        success = main()
        print('转换完成，成功状态:', success)
    except Exception as e:
        print(f'转换过程中发生错误: {{{{str(e)}}}}')
        success = False
";
            
            File.WriteAllText(scriptPath, script);
            return Task.FromResult(scriptPath);
        }
        
        /// <summary>
        /// 创建单个转换脚本（保留向后兼容性）
        /// </summary>
        private Task<string> CreateConversionScriptAsync(string svgFilePath, string outputFolder, string fontFamily)
        {
            var fileName = Path.GetFileNameWithoutExtension(svgFilePath);
            var scriptPath = Path.Combine(Path.GetTempPath(), $"convert_{fileName}_{Guid.NewGuid():N}.py");
            
            // 解析Unicode编码
            int unicode;
            if (!int.TryParse(fileName, System.Globalization.NumberStyles.HexNumber, null, out unicode))
            {
                throw new ArgumentException($"文件名 {fileName} 不是有效的十六进制Unicode编码");
            }
            
            // 转换字体名称为ASCII兼容格式
            var asciiFontFamily = ConvertToAsciiCompatible(fontFamily ?? "CustomFont");
            
            var script = $@"# -*- coding: utf-8 -*-
import fontforge
import os
import sys

def main():
    try:
        # 创建字体
        font = fontforge.font()
        font.encoding = 'UnicodeFull'
        font.version = '1.0'
        font.weight = 'Regular'
        font.fontname = '{asciiFontFamily}_{fileName}'
        font.familyname = '{asciiFontFamily}'
        font.fullname = '{fontFamily ?? "Custom Font"} {fileName}'
        
        # 创建字符
        glyph = font.createChar({unicode}, 'uni{fileName}')
        
        # 导入SVG轮廓
        glyph.importOutlines(r'{svgFilePath.Replace("\\", "/")}')
        
        # 设置字符宽度（可选）
        glyph.width = 1000
        
        # 确保输出目录存在
        output_dir = r'{outputFolder.Replace("\\", "/")}'
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        
        # 生成TTF文件
        output_path = os.path.join(output_dir, '{fileName}.ttf')
        font.generate(output_path)
        
        print(f'Successfully converted {{output_path}}')
        return True
        
    except Exception as e:
        print(f'Error: {{str(e)}}')
        return False
    finally:
        if 'font' in locals():
            font.close()

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
";
            
            File.WriteAllText(scriptPath, script);
            return Task.FromResult(scriptPath);
        }
        
        /// <summary>
        /// 执行FontForge脚本（优化版本，支持实时输出监控）
        /// </summary>
        private async Task<bool> ExecuteFontForgeScriptAsync(string fontForgePath, string scriptPath, 
            CancellationToken cancellationToken, PerformanceSettings performanceSettings = null)
        {
            var ffpythonPath = Path.Combine(fontForgePath, "ffpython.exe");
            
            var processStartInfo = new ProcessStartInfo
            {
                FileName = ffpythonPath,
                Arguments = $"\"{scriptPath}\"",
                WorkingDirectory = fontForgePath,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8
            };
            
            using (var process = new Process { StartInfo = processStartInfo })
            {
                var outputBuilder = new StringBuilder();
                var errorBuilder = new StringBuilder();
                
                // 设置输出数据接收事件
                process.OutputDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        outputBuilder.AppendLine(e.Data);
                        // 输出进度信息到调试控制台
                        System.Diagnostics.Debug.WriteLine($"FontForge: {e.Data}");
                    }
                };
                
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        errorBuilder.AppendLine(e.Data);
                        System.Diagnostics.Debug.WriteLine($"FontForge Error: {e.Data}");
                    }
                };
                
                try
                {
                    process.Start();
                    
                    // 开始异步读取输出
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    
                    // 等待进程完成或取消，使用配置的超时时间
                    var timeoutSeconds = performanceSettings?.ProcessTimeoutSeconds ?? 1800; // 默认30分钟
                    var timeoutMs = timeoutSeconds * 1000;
                    var startTime = DateTime.Now;
                    
                    while (!process.HasExited && !cancellationToken.IsCancellationRequested)
                    {
                        // 检查是否超时
                        if ((DateTime.Now - startTime).TotalMilliseconds > timeoutMs)
                        {
                            System.Diagnostics.Debug.WriteLine($"FontForge进程执行超时（{timeoutSeconds}秒），强制终止");
                            break;
                        }
                        
                        await Task.Delay(100, cancellationToken);
                    }
                    
                    if (cancellationToken.IsCancellationRequested || !process.HasExited)
                    {
                        if (!process.HasExited)
                        {
                            try
                            {
                                process.Kill();
                                await Task.Delay(1000); // 等待进程完全终止
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine($"终止进程时出错: {ex.Message}");
                            }
                        }
                        
                        if (cancellationToken.IsCancellationRequested)
                        {
                            return false;
                        }
                        
                        // 如果是因为超时而退出循环
                        if (!process.HasExited)
                        {
                            return false;
                        }
                    }
                    
                    // 等待进程完全退出
                    if (!process.HasExited)
                    {
                        process.WaitForExit(5000); // 最多等待5秒
                    }
                    
                    var success = process.ExitCode == 0;
                    
                    if (!success)
                    {
                        var errorOutput = errorBuilder.ToString();
                        if (!string.IsNullOrEmpty(errorOutput))
                        {
                            System.Diagnostics.Debug.WriteLine($"FontForge转换失败，错误信息: {errorOutput}");
                        }
                    }
                    
                    return success;
                }
                catch (OperationCanceledException)
                {
                    if (!process.HasExited)
                    {
                        try
                        {
                            process.Kill();
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"取消时终止进程出错: {ex.Message}");
                        }
                    }
                    return false;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"执行FontForge脚本时出错: {ex.Message}");
                    if (!process.HasExited)
                    {
                        try
                        {
                            process.Kill();
                        }
                        catch
                        {
                            // 忽略终止进程时的错误
                        }
                    }
                    return false;
                }
            }
        }
    }
}